/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.httpclient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import org.zhiqim.kernel.util.Closes;
import org.zhiqim.kernel.util.Files;
import org.zhiqim.kernel.util.Streams;
import org.zhiqim.kernel.util.Validates;

/**
 * HTTPS文件下载类
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class HttpDownload extends HttpClient
{
    private String fileDir;
    private String fileName;
    private File file;
    
    public HttpDownload(String url)
    {
        super(url, _GET_);
    }
    
    public void setFileDir(String fileDir)
    {
        this.fileDir = fileDir;
    }
    
    public void setFileName(String fileName)
    {
        this.fileName = fileName;
    }
    
    public String getFileDir()
    {
        return fileDir;
    }
    
    public File getFile()
    {
        return file;
    }
    
    public String getFileName()
    {
        return fileName;
    }
    
    protected boolean doPreRequestProperty()
    {
        if (Files.exists(fileDir))
        {
            if (!Files.isDirectory(fileDir))
            {
                responseStatus = _72_PARAM_NOT_SATISFIED_;
                responseText = "请求的文件存放目录不正确";
                return false;
            }
        }
        else
        {
            if (!Files.mkDirectory(fileDir))
            {
                responseStatus = _72_PARAM_NOT_SATISFIED_;
                responseText = "请求的文件存放目录不正确";
                return false;
            }
        }
        
        //如果没有指定类型，则设置支持全部类型
        if (!hasRequestProperty("Accept"))
            addRequestProperty("Accept", "*/*");
        
        return true;
    }
    
    protected void doReadResponseContent(HttpURLConnection conn) throws IOException
    {
        if (responseStatus == _302_FOUND_)
        {//重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_)
        {//错误
            responseText = getResponseError(conn);
            return;
        }
        
        //成功，获取文件名，如果用户未指定文件名则取连接中是否有文件名
        if (Validates.isEmpty(fileName))
            fileName = getFileName(conn);
        
        if (Validates.isEmpty(fileName))
        {//如果未指定且连接属性中没有则查看URL中有没有，判断方法是看有没有2-5位后缀
            String fileExt = Files.getFileExt(url);
            if (Validates.isAlphabeticLen(fileExt, 2, 5))
                fileName = Files.getFileName(url, "/");
        }
        
        if (Validates.isEmpty(fileName))
        {//未配置、连接属性中没有、URL没有则报错
            responseStatus = _72_PARAM_NOT_SATISFIED_;
            responseText = "未指定文件名称";
            return;
        }
        
        file = new File(fileDir, fileName);
        FileOutputStream output = new FileOutputStream(file);
        InputStream input = conn.getInputStream();
        
        try
        {
            Streams.putBytes(input, output);
        }
        finally
        {
            Closes.closeIgnoreException(output, input);
        }
        
        responseText = "下载成功";
    }
}
